import shutil
import os
import logging
import sys
from pathlib import Path
from time import perf_counter

from tqdm import tqdm

logger = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)


def cp_or_mv2(src_full: Path, des_path: Path, is_copy):
    print(src_full)
    if src_full.is_file():
        # logger.info(f'from file {src_full}')
        if is_copy:
            shutil.copy2(src_full, des_path)
            logger.info(f'copied {des_path}')
        else:
            shutil.move(src_full, des_path)
            logger.info(f'move to {des_path}')
    else:
        logger.info(f'from dir {src_full}')
        shutil.copytree(src_full, des_path, dirs_exist_ok=True)
        logger.info(f'to {des_path}')
        if not is_copy:
            shutil.rmtree(src_full)
            logger.info(f'deleted {src_full}')


def process_files_in_txt(txt_file, src_dir, des_dir, is_copy, overwrite_existing):
    """
    复制或移动文件（夹）
    :param txt_file: 配置哪些文件（夹）需要处理
    :param src_dir: 源目录
    :param des_dir: 目标目录
    :param is_copy: 只复制，如果False，则剪切
    :param overwrite_existing: 覆盖已有，如果False，跳过
    :return:
    """
    logger.info(f'源 {src_dir}')
    logger.info(f'目标 {src_dir}')
    logger.info(f'只复制 {is_copy}')
    logger.info(f'覆盖 {overwrite_existing}')
    des_top_path = Path(des_dir)
    with open(txt_file, 'r', encoding='utf8', errors='ignore') as f:
        file_names = set([x.strip() for x in f.readlines() if len(x) > 2])
        # print(file_names)
    src_top_path = Path(src_dir)
    total = 0
    t1 = perf_counter()
    for src_path in tqdm(src_top_path.rglob("*")):
        total += 1
        # print(src_path)
        name = src_path.name
        if name in file_names:
            # logger.debug(f'{src_path}')
            des_path = des_top_path / name
            if des_path.exists() and not overwrite_existing:
                logger.info(f'{src_path}已经存在，且不覆盖，跳过。')
                continue
            cp_or_mv2(src_path, des_path, is_copy)
    t2 = perf_counter()
    used_time = int(t2 - t1)
    logger.info(f'完成扫描{src_top_path}，共{total}个文件(夹)，用时{used_time}秒')


if __name__ == '__main__':
    process_files_in_txt(r"C:\Users\yang.lei\Downloads\需要拷贝.txt",  # 哪些文件（夹）
                         r"C:\G",  # 从哪个文件夹
                         r"C:\Users\yang.lei\Downloads\des",  # 到哪个文件夹
                         is_copy=True, overwrite_existing=False)  # True复制，False剪切
